import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/ge_an_entity.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/widgets/gallery_photo_browser.dart';

import '../../login/page/user_manager.dart';

class GeAnDetailPage extends StatefulWidget {
  final int? id;
  final int? type;
  GeAnDetailPage({Key? key, this.id, this.type});
  @override
  _GeAnDetailPageState createState() => _GeAnDetailPageState();
}

class _GeAnDetailPageState extends State<GeAnDetailPage> {
  GeAnBeanDetail? detailModel;
  String users = '';
  String age = '';
  String statusStr = '';
  List<int> imageIdList = [];
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectDetail();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('详情'),
        elevation: 0.5,
      ),
      body: SingleChildScrollView(
        child: detailModel != null
            ? Container(
                padding: EdgeInsets.all(20),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          '${detailModel!.bean?.elderName??""} ',
                          style: TextStyles.textBoldDark16,
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        Expanded(
                          child: Text(
                            '$age  ${detailModel!.bean?.bedNo??""}',
                            style: TextStyles.textGray14,
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.all(5),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.grey,
                              borderRadius: BorderRadius.circular(3)),
                          child: Text(
                            '$statusStr',
                            style: TextStyle(color: Colors.white, fontSize: 16),
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      '发起原因：${detailModel!.bean?.reason??""}',
                      style: TextStyles.textNormal16,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      '发起人：${detailModel!.caption?.createdBy??""}',
                      style: TextStyles.textNormal16,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      '发起时间：${detailModel?.bean?.createdDate??""}',
                      style: TextStyles.textNormal16,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      '参与人员：$users',
                      style: TextStyles.textNormal16,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      '附件：',
                      style: TextStyles.textNormal16,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    (detailModel?.bean?.attachFiles??[]).length <= 0
                        ? SizedBox()
                        : GridView.count(
                            shrinkWrap: true,
                            crossAxisCount: 5,
                            mainAxisSpacing: 10,
                            crossAxisSpacing: 10,
                            children: (detailModel?.bean?.attachFiles??[])
                                .map((f) => _picture(f))
                                .toList(),
                          ),
                    SizedBox(
                      height: 20,
                    ),
                    Text(
                      '处理记录',
                      style: TextStyles.textBoldDark16,
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    (detailModel?.bean?.records != null &&
                            (detailModel?.bean?.records??[]).length > 0)
                        ? Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: (detailModel?.bean?.records??[])
                                .map((f) => _item(f))
                                .toList(),
                          )
                        : SizedBox()
                  ],
                ),
              )
            : Container(
                height: ScreenUtil.getScreenH(context),
                child: Center(
                  child: Text(
                    '暂无数据',
                    style: TextStyles.textGray14,
                  ),
                ),
              ),
      ),
    );
  }

  Widget _picture(AttachFilesInfo info) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GalleryPhotoViewWrapper(
              galleryItems: imageIdList,
              backgroundDecoration: const BoxDecoration(
                color: Colors.black,
              ),
              initialIndex: imageIdList.indexOf(info.id!),
            ),
          ),
        );
      },
      child: Container(
        child: CachedNetworkImage(
          fit: BoxFit.cover,
          imageUrl: '${HttpApi.imageDownLoadUrl}${info.id}',
            httpHeaders: {"Cookie":UserManager.cookieStr},
          placeholder: (context, url) => new ProgressView(),
          errorWidget: (context, url, error) => new Icon(Icons.error),
        ),
        decoration: BoxDecoration(
          color: Colours.bg_color,
          borderRadius: BorderRadius.circular(5),
        ),
      ),
    );
  }

  Widget _item(RecordInfo info) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 10),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Text(
              ' ${info.operator}',
              style: TextStyles.textDark16,
            ),
            Gaps.hGap15,
            Text(
              '${info.createdDate}',
              style: TextStyles.textGray12,
            ),
          ],
        ),
        SizedBox(
          height: 5,
        ),
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(12),
          child: Text(
            '${info.remark}',
            style: TextStyles.textNormal16,
          ),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5), color: Colours.bg_color),
        ),
        Gaps.vGap12,
        Gaps.line,
      ],
    );
  }

  ///获取数据
  _fectDetail() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {'id': widget.id, 'wrapper': true};
    String url = widget.type == 0 ? HttpApi.gebanDetail : HttpApi.huibanDetail;
    HttpUtil.instance.getDio().post(url, data: map,options: PostRequest.urlencodedHeader).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            GeAnBeanDetail model = GeAnBeanDetail.fromJson(map['data']);
            setState(() {
              detailModel = model;
              switch (model.bean?.status) {
                case 0:
                  statusStr = '待处理';
                  break;
                case 1:
                  statusStr = '待审核';
                  break;
                case 2:
                  statusStr = '已驳回';
                  break;
                case 3:
                  statusStr = '已完成';
                  break;
                default:
              }
              age = detailModel?.bean?.age != null ? '${model.bean?.age}岁' : '';
              for (UserInfo item in (model.bean?.executeHumanList??[])) {
                users = users + item.name! + '，';
              }
              for (AttachFilesInfo item in (model.bean?.attachFiles??[])) {
                imageIdList.add(item.id!);
              }
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
